<template>
  <div class="download-bg">
    <div class="download-conntainer">
      <div class="doc-content">
        <!-- 文件信息预览 -->
        <div class="doc-review">
          <div id="domRef" ref="domRef" class="doc-info whole-node">
            <div class="doc-item">
              <div class="bstract-table">
                <div class="title-name">收文传阅单</div>
                <a-table
                  :columns="columns"
                  :data-source="dataSource"
                  :show-header="false"
                  bordered
                  :pagination="false"
                  class="ss"
                >
                  <template #bodyCell="{ text, column, record }">
                    <!-- 标题 -->
                    <div v-if="column.dataIndex === 'title'" class="cell-title">{{ text }}</div>
                    <!-- 内容 -->
                    <template
                      v-else-if="record.type === 'TextRichField' && props.textType * 1 === 1"
                    >
                      <div
                        v-if="record.content"
                        class="cell-contents whole-node"
                        v-html="record.content"
                      >
                      </div>
                      <div v-else class="nodata"> &nbsp; </div>
                    </template>
                    <template
                      v-else-if="record.type === 'TextRichField' && props.textType * 1 === 2"
                    >
                      <div v-if="record.content" class="cell-contents whole-node">
                        {{ record.content }}
                      </div>
                      <div v-else class="nodata"> &nbsp; </div>
                    </template>
                    <!-- 附件 暂时不知道啥格式 -->
                    <template v-else-if="record.type === 'DDAttachment'">
                      <div v-if="text" class="file-info cell-contents whole-node">
                        <div v-for="i in getUrl(text)" :key="i" class="file-item">
                          <div class="whole-node" @click="previewFile(i)">
                            <span>{{ i.name }}</span>
                          </div>
                          <!-- <div @click="downloadFile(i)">
                          <svg-icon icon-class="btn_icon_download" class-name="btn-icon-download">
                          </svg-icon>
                        </div> -->
                        </div>
                      </div>
                      <div v-else class="nodata"> &nbsp; </div>
                    </template>

                    <!-- 审批流程 -->
                    <div v-else-if="record.dataIndex === 'approval'" class="cell-approval">
                      <div class="comment whole-node">{{ record.data.notes }}</div>
                      <div class="people whole-node"
                        >{{ record.data.name
                        }}<template v-if="record.data.nodeType === 1">（发起审批） </template
                        ><template v-else>（{{ statusObj[record.data.status] }}） </template>
                      </div>
                      <div class="time whole-node">{{ record.data.time }}</div>
                    </div>
                    <!-- 普通表单 -->
                    <template v-else>
                      <div v-if="text" class="cell-content whole-node">{{ text }}</div>
                      <div v-else class="nodata">&nbsp;</div>
                    </template>
                  </template>
                </a-table>
              </div>
            </div>
            <div v-if="downloadText" class="doc-item">
              <span class="content-name whole-node">正文</span>
              <div class="whole-node" v-html="text"></div>
            </div>
            <!-- <div v-if="downloadRecord" class="doc-item">
              <span class="content-name">审批记录</span>
              <div></div>
            </div> -->
            <!-- </div> -->
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { ref, defineProps, onMounted, defineExpose } from 'vue';
import html2canvas from 'html2canvas';
import JsPDF from 'jspdf';
import printJS from 'print-js';
let props = defineProps({
  textType: {},
  tableData: {
    // table数据
    type: Array,
    default: () => [
      {
        title: '公文标题',
        content: '等哈就开始打啥的客户'
      },
      {
        title: '紧急程度',
        content: '等哈就开始打啥的客户'
      },
      {
        dataIndex: 'approval',
        title: '拟办',
        content: '等哈就开始打啥的客户',
        data: {
          name: '张三',
          time: '20323 2 11',
          notes: '同意 不同意'
        }
      },
      {
        title: 'dfd',
        content: '等哈就开始打啥的客户'
      },
      {
        title: '撒旦发射点',
        content: '等哈就开始打啥的客户'
      }
    ]
  }
});
let statusObj = ref({
  // 审批状态
  0: '未审核',
  1: '已通过',
  2: '审核中',
  3: '已撤销',
  4: '已拒绝',
  5: '已转办',
  6: '已加签',
  7: '已退回',
  8: '已废弃',
  null: ''
});
onMounted(() => {
  dataSource.value = props.tableData;
  console.log(props.tableData);
  init('domRef');
});

let domValue = ref('');
defineExpose({ init });
function init(domId) {
  // title=>名字,type=》下载还是 打印
  let pdfDom = domId;
  const A4_WIDTH = 592.28;
  const A4_HEIGHT = 841.89;
  // myLoading 自定义等待动画组件，实现导出事件的异步等待交互
  // dom的id。
  let target = document.getElementById(pdfDom);
  // console.log(target.scrollWidth);
  // let pageHeight = (target.scrollWidth / A4_WIDTH) * A4_HEIGHT;
  // console.log('pageHeight', pageHeight);
  // 获取分割dom，此处为class类名为ant-table-row的dom
  // let a = document.getElementsByClassName('ant-table-tbody');
  // console.log(a);
  let lableListID = target.getElementsByClassName('ant-table-row');
  console.log('多少个tr', lableListID);

  // console.log(lableListID);
  // 进行分割操作，当dom内容已超出a4的高度，则将该dom前插入一个空dom，把他挤下去，分割
  for (let i = 0; i < lableListID.length; i++) {
    console.log('高度', lableListID[i].offsetHeight);
    // let multiple = Math.ceil((lableListID[i].offsetTop + lableListID[i].offsetHeight) / pageHeight);
    if (lableListID[i].offsetHeight > 841) {
      // 这个判断是 如果当前的一个tr的高度大于A4值的高度， 直接将这个tr拆分成多个tr 在拼接到原理的位置
      // console.log(lableListID[i].innerHTML);

      // 获取原始的<tr>元素
      let originalTr = lableListID[i];
      // console.log(originalTr.children[1].children[0].innerHTML);
      // domValue.value = originalTr.children[0].innerHTML;
      domValue.value = JSON.stringify(originalTr.children[1].children[0].innerHTML);
      // 获取原始的<tr>元素的高度
      let originalTrHeight = originalTr.offsetHeight;

      // 计算需要拆分的行数
      let rowsToSplit = Math.ceil(originalTrHeight / 841) + 3;
      console.log('拆分多少个', rowsToSplit);
      let lengthNum = Math.ceil(lableListID[i].innerHTML.length / rowsToSplit);
      // console.log('分割多少页', lengthNum);

      // 获取需要分割的元素
      let parentElement = originalTr.children[1];

      // 获取元素的高度
      let totalHeight = parentElement.offsetHeight;
      // console.log(totalHeight);
      // 计算每一部分的高度
      // let partHeight = Math.ceil(totalHeight / rowsToSplit);
      // console.log(partHeight);
      // let newElements = [];

      // 创建一个数组来存储新的<tr>元素
      let newTrs = [];

      // 循环创建新的<tr>元素并复制原始<tr>中的单元格到新的行中
      for (let t = 0; t < rowsToSplit; t++) {
        let newTr = document.createElement('tr');

        // 获取原始<tr>中的单元格并复制到新的行中
        let cells = originalTr.querySelectorAll('td');

        for (let j = 0; j < cells.length; j++) {
          // console.log(cells[1].children[0].innerHTML);
          // 循环创建新的<tr>元素并复制原始<tr>中的单元格到新的行中
          let newCell = cells[j].cloneNode(true); // 精准拷贝
          newTr.appendChild(newCell);
        }
        // console.log(222, newTr);
        newTr.className = 'ant-table-row zz';
        // newTr.style.pageBreakAfter = 'always';
        // 将新的<tr>元素添加到页面中
        newTrs.push(newTr);

        // init(domId);
      }
      // console.log(newTrs);
      // let newTrsList = [];
      for (let i = 0; i < newTrs.length; i++) {
        // console.log(newTrs[i]);
        // console.log(
        //   newTrs[i].children[1].children[0].innerHTML.slice(i * lengthNum, (i + 1) * lengthNum)
        // );
        newTrs[i].children[1].children[0].innerHTML = newTrs[
          i
        ].children[1].children[0].innerHTML.slice(i * lengthNum, (i + 1) * lengthNum);
      }
      // newTrs.forEach((item, index) => {
      //   // console.log(item.children[1].children[0].innerHTML);
      //   console.log(index * lengthNum, (index + 1) * lengthNum);
      //   // newTrsList.push(
      //   item.children[1].children[0].innerHTML = item.children[1].children[0].innerHTML.substring(
      //     index * lengthNum,
      //     (index + 1) * lengthNum
      //   );
      // });
      // 删除原始的<tr>元素
      originalTr.remove();
      // console.log(333, newTrs);
      // console.log(newTrsList);
      // 将新的<tr>元素添加到页面中

      newTrs.forEach(newTr => {
        // console.log(lableListID[i]);
        // setTimeout(() => {
        lableListID[i].parentNode.insertBefore(newTr, lableListID[i]);
        // });
        // target.getElementsByClassName('ant-table-row').appendChild(newTr);
      });
    }
  }
}
function getUrl(urlList) {
  console.log(urlList);
  let url = urlList.split('\\');
  let list = [];
  url.forEach(item => {
    list.push({
      name: item.slice(item.lastIndexOf('/') + 1),
      url: item
    });
  });
  return list;
}
const columns = [
  {
    title: 'title',
    dataIndex: 'title',
    width: '120px'
  },
  {
    title: 'content',
    dataIndex: 'content',
    width: '520px'
  }
];
// let titleArr = [
//   '公文标题',
//   '文号',
//   '紧急程度',
//   '密级',
//   '发文单位',
//   '主送单位',
//   '抄送单位抄送单位抄送单位',
//   '内容',
//   '附件'
// ];
const dataSource = ref([]);

const domRef = ref(null);
function downloadFileZip1() {
  let targetDom = domRef.value;
  let scale = 2;
  html2canvas(targetDom, {
    scale: scale, // 提升画面质量，但是会增加文件大小
    useCORS: true, // 允许跨域图片 当图片是链接地址时，需加该属性，否组无法显示图片
    imageTimeout: 0, // 图片加载延迟，默认延迟为0，单位毫秒
    height: targetDom.scrollHeight, // canvas的高度设定
    width: targetDom.scrollWidth, // canvas的宽度设定
    dpi: window.devicePixelRatio * scale // 将分辨率提高到特定的DPI
  }).then(canvas => {
    // a4纸的尺寸[592.28,841.89]
    const A4_WIDTH = 592.28;
    const A4_HEIGHT = 841.89;
    let contentWidth = canvas.width;
    let contentHeight = canvas.height;
    let pageData = canvas.toDataURL('image/jpeg', 0.6);
    // 一页pdf html页面生成的canvas高度;
    let pageHeight = (contentWidth / A4_WIDTH) * A4_HEIGHT;
    // 未生成pdf的html页面高度
    let leftHeight = contentHeight;
    // 页面偏移
    let position = 0;
    // a4纸的尺寸[592.28,841.89]，html页面生成的canvas在pdf中图片的宽高
    let imgWidth = A4_WIDTH;
    let imgHeight = (A4_WIDTH / contentWidth) * contentHeight;
    // 设置pdf的尺寸，pdf要使用pt单位 已知 1pt/1px = 0.75   pt = (px/scale)* 0.75
    let pdf = new JsPDF('', 'pt', 'a4');
    // 有两个高度需要区分，一个是html页面的实际高度，和生成pdf的页面高度
    // 当内容未超过pdf一页显示的范围，无需分页
    if (leftHeight < pageHeight) {
      pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight);
    } else {
      while (leftHeight > 0) {
        pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
        leftHeight -= pageHeight;
        position -= A4_HEIGHT;
        // 避免添加空白页
        if (leftHeight > 0) {
          pdf.addPage();
        }
      }
    }
    // 直接下载
    pdf.save(11111 + '.pdf');
  });
}

function printAllPdf() {
  let title = '批量下载或单文件名字';
  // 如果这个页面有左右移动,canvas 也要做响应的移动，不然会出现canvas 内容不全
  const xOffset = 0; // window.pageXOffset;
  // 避免笔下误 灯下黑 统一写
  const A4_WIDTH = 592.28;
  // const A4_HEIGHT = 841.89
  const A4_HEIGHT = 880;
  let printDom = domRef.value[0];
  // 根据A4的宽高计算DOM页面一页应该对应的高度
  let pageHeight = (printDom.offsetWidth / A4_WIDTH) * A4_HEIGHT;
  // 将所有不允许被截断的元素进行处理
  let wholeNodes = document.querySelectorAll('.whole-node');
  console.log('wholeNodes:', wholeNodes);
  for (let i = 0; i < wholeNodes.length; i++) {
    // 1、 判断当前的不可分页元素是否在两页显示
    const topPageNum = Math.ceil(wholeNodes[i].offsetTop / pageHeight);

    const bottomPageNum = Math.ceil(
      (wholeNodes[i].offsetTop + wholeNodes[i].offsetHeight) / pageHeight
    );

    if (topPageNum !== bottomPageNum) {
      // 说明该dom会被截断
      // 2、插入空白块使被截断元素下移
      let divParent = wholeNodes[i].parentNode;
      let newBlock = document.createElement('div');
      newBlock.className = 'empty-div';
      newBlock.style.background = '#fff';

      // 3、计算插入空白块的高度 可以适当流出空间使得内容太靠边，根据自己需求而定
      let _H = topPageNum * pageHeight - wholeNodes[i].offsetTop;
      newBlock.style.height = _H + 30 + 'px';
      divParent.insertBefore(newBlock, wholeNodes[i]);
    }

    // 以上完成dom层面的分页 可以转为图片进一步处理了

    html2canvas(printDom, {
      height: printDom.offsetHeight,
      width: printDom.offsetWidth,
      scrollX: -xOffset,
      allowTaint: true,
      scale: 2.5 // 模糊问题
    }).then(canvas => {
      // dom 已经转换为canvas 对象，可以将插入的空白块删除了
      let emptyDivs = document.querySelectorAll('.empty-div');
      for (let i = 0; i < emptyDivs.length; i++) {
        emptyDivs[i].parentNode.removeChild(emptyDivs[i]);
      }
      // 有一点重复的代码
      let contentWidth = canvas.width;
      let contentHeight = canvas.height;
      let pageHeight = (contentWidth / A4_WIDTH) * A4_HEIGHT;
      let leftHeight = contentHeight;
      let position = 0;

      let imgWidth = A4_WIDTH;
      let imgHeight = (A4_WIDTH / contentWidth) * contentHeight;
      let pageData = canvas.toDataURL('image/jpeg', 1.0);

      // 打印，可以拿着分号页的数据 直接使用
      printJS({
        printable: [pageData, pageData],
        type: 'image',
        base64: true,
        documentTitle: '\u200E'
      });
    });
  }
}
</script>
<style lang="less" scoped>
@import './index.less';
.title-name {
  text-align: center;
  font-size: 24px;
  font-weight: 500;
  position: relative;
  top: -31px;
  // margin-bottom: 40px;
}
.tdhaha {
  border: none !important;
  border-bottom: 1px solid black !important;
  background: #fff !important;
  border-left: 2px solid #ffffff !important;
}
/deep/ .ant-table-tbody {
  page-break-inside: avoid !important;
}
/deep/ .ant-table-row {
  page-break-inside: avoid !important;
}
</style>
